const express = require('express');
const es = require('express-session');

const app = express();

app.use(
  es({
    secret: 'qwe123',
    resave: false,
    saveUninitialized: true,
  })
);

// 登录
app.post('/user/login', express.json(), (req, res) => {
  const { username, password } = req.body;
  if (username === 'zs' && password === 'qwe123') {
    console.log('账号密码正确，登录成功');
    req.session.username = username; // 保存用户名
    req.session.isLogin = true; // 标识是否已登录
    res.send({
      code: 200,
      msg: 'ok',
    });
  } else {
    res.send({
      code: 400,
      msg: '账号或密码不正确',
    });
  }
});

// 获取用户信息
app.get('/user/info', (req, res) => {
  res.send(req.session.username);
});

// 退出登录
app.get('/user/logout', (req, res) => {
  req.session.destroy((err) => {
    if (err) res.send({ code: 500, msg: err.message });
    else res.send({ code: 200, msg: 'ok' });
  });
});

app.listen(80, () => {
  console.log('running at http://lcoalhost');
});
